/**
 * Created by John on 2016/7/7.
 */
var mongo = new Mongo('localhost');
var wordsDB = mongo.getDB('BeginningMongoDB');
var wordsColl = wordsDB.getCollection('word_stats');

var result = wordsColl.mapReduce(
    function () {
        emit(this.first, this.stats.vowels);
    },

    function (key, values) {
        return Array.sum(values);
    },

    {
        out: {inline: 1}
    }
);
print("Total vowel count in words beginning with a certain letter:");
result.results.forEach(function (item) {
    print(JSON.stringify(item));

});

result = wordsColl.mapReduce(
    function () {
        emit(this.first,
            {
                vowels: this.stats.vowels,
                consonants: this.stats.consonants
            });
    },

    function (key, values) {
        var result = {
            count: values.length,
            vowels: 0,
            consonants: 0
        };

        for (var i = 0; i < values.length; i++) {
            if (values[i].vowels) {
                result.vowels += values[i].vowels;
            }
            if (values[i].consonants) {
                result.consonants += values[i].consonants;
            }
        }

        return result;
    },

    {
        out: {inline: 1},
        query: {last: {$in: ['a', 'e', 'i', 'o', 'u']}},
        finalize: function (key, obj) {
            obj.charsets = obj.vowels + obj.consonants;
            return obj;
        }
    }
);
print("Total words, vowels, consonants and characters in words beginning with a certain letter that ends with a vowels:");
result.results.forEach(function (item) {
    print(JSON.stringify(item));
});